package com.example.behaviour.controller.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.apis.article.iArticleClient;
import com.example.behaviour.config.SpringUtils;
import com.example.behaviour.mapper.*;
import com.example.behaviour.message.LatestMsgListResponseMessage;
import com.example.behaviour.pojos.*;
import com.example.behaviour.service.CommentService;
//import com.example.behaviour.webSocket.WebSocket;
//import com.example.behaviour.webSocket.WebSocket;
import com.example.common.constants.MessageConstants;
import com.example.common.redis.RedisCache;
import com.example.model.acl.pojos.Acl_user;
import com.example.model.article.pojos.ApArticle;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.common.enums.AppHttpCodeEnum;
import com.example.model.user.pojos.AclUserFan;
import com.example.model.user.pojos.ApUser;
import com.example.model.user.pojos.ApUserFollow;
import com.example.user.mapper.AclUserMapper;
import com.example.user.mapper.ApUserMapper;
import com.example.utils.common.AppJwtUtil;
import com.heima.file.service.FileStorageService;
import com.sun.xml.bind.v2.TODO;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/api/v1/behaviour")
public class BehaviourController {

    @Autowired
    private AclUserFanMapper aclUserFanMapper;

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private AclUserMapper aclUserMapper;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private ApUserRelationMapper apUserRelationMapper;

    @Autowired
    private ApUserFriendRequestMapper apUserFriendRequestMapper;

    @Autowired
    private ApUserMsgListMapper apUserMsgListMapper;

//    @Autowired
//    private WebSocket webSocket;

    @PostMapping("/test")
    public ResponseResult test(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        return ResponseResult.okResult(userId);
    }

    @PostMapping("/register")
    public ResponseResult register(@RequestBody RegisterDto registerDto){
        System.out.println("register" + registerDto.toString());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",registerDto.getPhone());
        ApUser apUser = apUserMapper.selectOne(queryWrapper);
        if(apUser != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该手机号已被注册");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("name",registerDto.getName());
        ApUser apUser1 = apUserMapper.selectOne(queryWrapper1);
        if(apUser1 != null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该用户名已被使用");
        }

        ApUser apUser2 = new ApUser();
        apUser2.setImage("../static/headImg");
        apUser2.setSalt("123");
        apUser2.setName(registerDto.getName());
        apUser2.setPhone(registerDto.getPhone());
        String pswd = DigestUtils.md5DigestAsHex((registerDto.getPassword() + apUser2.getSalt()).getBytes());
        apUser2.setPassword(pswd);

        apUserMapper.insert(apUser2);
        return ResponseResult.okResult("注册成功");
    }

    @PostMapping("/userInfo")
    public ResponseResult getUserInfo(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        return ResponseResult.okResult(apUserMapper.selectById(userId));
    }

    @PostMapping("/commentsByUserId/{id}")
    public ResponseResult commentsByUserId(@PathVariable("id") Integer id){
        return commentService.findCommentsByUserId(id);
    }

    @PostMapping("/updateUserDetail")
    public ResponseResult updateUserDetail(@RequestBody UserDetailDto dto, HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        ApUser apUser = apUserMapper.selectById(userId);
        apUser.setBgImage(dto.getBgImage());
        apUser.setImage(dto.getImage());
        if(dto.getSex() == 1){
            apUser.setSex(true);
        }else{
            apUser.setSex(false);
        }
        apUser.setInfo(dto.getInfo());

        apUserMapper.updateById(apUser);
        return ResponseResult.okResult("更新成功");
    }

    @PostMapping("/wemediaInfo/{id}")
    public ResponseResult getWemediaInfo(HttpServletRequest request,@PathVariable("id") Integer id){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        Acl_user acl_user = aclUserMapper.selectById(id);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("follow_id",id);
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(queryWrapper);
        if(apUserFollow == null){
            acl_user.setFollowed(false);
        }else{
            acl_user.setFollowed(true);
        }
        return ResponseResult.okResult(acl_user);
    }

    @Autowired
    private ApCollectionDtoMapper apCollectionDtoMapper;

    @PostMapping("/collectionList")
    public ResponseResult getCollectionList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        return ResponseResult.okResult(apCollectionDtoMapper.getCollectionList(userId));
    }

    @PostMapping("/searchUser/{name}")
    public ResponseResult searchUser(@PathVariable("name") String name,HttpServletRequest request){
        QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.eq("status",1);

        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());
        ApUser user = apUserMapper.selectById(userId);

        List<ApUser> apUserList = apUserMapper.selectList(queryWrapper);

        for (int i = 0; i < apUserList.size(); i++) {
            if(apUserList.get(i).getName().equals(user.getName())){
                apUserList.remove(i);
            }
        }

        apUserList.stream().map(apUser->{
            QueryWrapper<ApUserRelation> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("friendName",apUser.getName());
            queryWrapper1.eq("userName",user.getName());
//            log.info("friendName {}",apUser.getName());
//            log.info("userName {}",user.getName());
            ApUserRelation apUserRelation = apUserRelationMapper.selectOne(queryWrapper1);
            if(apUserRelation == null){
                apUser.setFriend(false);
            }else {
                apUser.setFriend(true);
            }
            return apUser;
        }).collect(Collectors.toList());
//        log.info("apUserList {}", Arrays.toString(apUserList.toArray()));

        return ResponseResult.okResult(apUserList);
    }

    @PostMapping("/getMsgList/{name}")
    public ResponseResult getMsgList(@PathVariable("name") String name){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",name);
        return ResponseResult.okResult(apUserMsgListMapper.selectList(queryWrapper));
    }

    @PostMapping("/delFriend/{fid}")
    public ResponseResult delFriend(@PathVariable("fid") Integer fid,HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("friendId",fid);
//        apUserFriendRequestMapper.delete(queryWrapper);
        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("userId",fid);
        queryWrapper2.eq("friendId",userId);

        apUserRelationMapper.delete(queryWrapper);
        apUserRelationMapper.delete(queryWrapper2);

        ApUser form = apUserMapper.selectById(userId);
        ApUser to = apUserMapper.selectById(fid);
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userName",form.getName());
        queryWrapper1.eq("friendName",to.getName());

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("friendName",form.getName());
        queryWrapper3.eq("userName",to.getName());

        apUserMsgListMapper.delete(queryWrapper1);
        apUserMsgListMapper.delete(queryWrapper3);

        return ResponseResult.okResult("删除好友成功");
    }

    @PostMapping("/friendList")
    public ResponseResult friendList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<ApUserRelation> list = apUserRelationMapper.selectList(queryWrapper);
        list.forEach((item)->{
            ApUser apUser = apUserMapper.selectById(item.getFriendId());
            item.setImage(apUser.getImage());
            item.setBgImage(apUser.getBgImage());
            item.setActive(false);
        });
        return ResponseResult.okResult(list);
    }

    @PostMapping("/agreeFriendRequest/{friendId}")
    public ResponseResult agreeFriendRequest(HttpServletRequest request,@PathVariable("friendId") String friendId){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",friendId);
        queryWrapper.eq("friendId",userId);
        List<ApUserFriendRequest> list = apUserFriendRequestMapper.selectList(queryWrapper);
        ApUserFriendRequest apUserFriendRequest = list.get(list.size() - 1);
        apUserFriendRequest.setSuccess(1);
        apUserFriendRequestMapper.updateById(apUserFriendRequest);

        ApUser me = apUserMapper.selectById(userId);
        ApUser other = apUserMapper.selectById(friendId);

        ApUserMsg apUserMsg = new ApUserMsg();
        apUserMsg.setFromUser(me.getName());
        apUserMsg.setFromId(me.getId());
        apUserMsg.setUserId(other.getId());
        apUserMsg.setType(1);
        apUserMsg.setCreatedTime(new Date());
        apUserMsg.setContent(me.getName()+"通过了您的好友请求");
        apUserMsg.setIsRead(0);
        apUserMsgMapper.insert(apUserMsg);

        ApUserRelation apUserRelation = new ApUserRelation();
        apUserRelation.setUserId(userId);
        apUserRelation.setFriendId(Integer.valueOf(friendId));
        apUserRelation.setCreatedTime(new Date());
        apUserRelation.setFriendName(other.getName());
        apUserRelation.setUserName(me.getName());
        apUserRelation.setAddInfo(apUserFriendRequest.getAddInfo());
        apUserRelationMapper.insert(apUserRelation);

        ApUserRelation apUserRelation1 = new ApUserRelation();
        apUserRelation1.setUserId(Integer.valueOf(friendId));
        apUserRelation1.setFriendId(userId);
        apUserRelation1.setCreatedTime(new Date());
        apUserRelation1.setFriendName(me.getName());
        apUserRelation1.setUserName(other.getName());
        apUserRelation1.setAddInfo(apUserFriendRequest.getAddInfo());
        apUserRelationMapper.insert(apUserRelation1);



        return ResponseResult.okResult("添加好友成功");
    }

    @PostMapping("/disAgreeFriendRequest/{friendId}")
    public ResponseResult disAgreeFriendRequest(HttpServletRequest request,@PathVariable("friendId") String friendId){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",friendId);
        queryWrapper.eq("friendId",userId);
        List<ApUserFriendRequest> list = apUserFriendRequestMapper.selectList(queryWrapper);
        ApUserFriendRequest apUserFriendRequest = list.get(list.size() - 1);
        apUserFriendRequest.setSuccess(-1);
        apUserFriendRequestMapper.updateById(apUserFriendRequest);

        ApUser me = apUserMapper.selectById(userId);
        ApUser other = apUserMapper.selectById(friendId);

        ApUserMsg apUserMsg = new ApUserMsg();
        apUserMsg.setFromUser(me.getName());
        apUserMsg.setFromId(me.getId());
        apUserMsg.setUserId(other.getId());
        apUserMsg.setType(1);
        apUserMsg.setCreatedTime(new Date());
        apUserMsg.setContent(me.getName()+"拒绝了您的好友请求");
        apUserMsg.setIsRead(0);
        apUserMsgMapper.insert(apUserMsg);

        return ResponseResult.okResult("添加好友成功");
    }

    @PostMapping("/addFriendRequest")
    public ResponseResult addFriend(@RequestBody ApUserFriendRequest apUserFriendRequest,HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());
        apUserFriendRequest.setUserId(userId);

        ApUser apUser = apUserMapper.selectById(userId);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",apUserFriendRequest.getUserId());
        queryWrapper.eq("friendId",apUserFriendRequest.getFriendId());
        System.out.println("apUserFriendRequest "+apUserFriendRequest.toString());

        List<ApUserFriendRequest> list = apUserFriendRequestMapper.selectList(queryWrapper);
        ApUserFriendRequest apUserFriendRequest1;
        if(list == null || list.size() == 0){
            apUserFriendRequest1 = null;
        }else{
            apUserFriendRequest1 = list.get(list.size()-1);
            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("userId",apUserFriendRequest.getUserId());
            queryWrapper1.eq("friendId",apUserFriendRequest.getFriendId());
            ApUserRelation apUserRelation = apUserRelationMapper.selectOne(queryWrapper1);
            if(apUserRelation != null){
                return ResponseResult.okResult("已经是好友了");
            }
        }

//        System.out.println("apUserFriendRequest1 "+apUserFriendRequest1.toString());
        //已经发送了一次，但还没处理

        if(apUserFriendRequest1 != null && apUserFriendRequest1.getSuccess() == 0){
            apUserFriendRequest1.setCreatedTime(new Date());
            apUserFriendRequest1.setAddInfo(apUserFriendRequest.getAddInfo());
            apUserFriendRequestMapper.updateById(apUserFriendRequest1);
            System.out.println("更新好友请求");
            return ResponseResult.okResult("好友请求发送成功");
        }
        //已经发生了一次，且拒绝，重新发送
        if(apUserFriendRequest1 != null && apUserFriendRequest1.getSuccess() == -1){
            apUserFriendRequest1.setSuccess(0);
            apUserFriendRequest1.setAddInfo(apUserFriendRequest.getAddInfo());
            apUserFriendRequest1.setCreatedTime(new Date());
            apUserFriendRequestMapper.updateById(apUserFriendRequest1);
        }

        //第一次发送
        apUserFriendRequest.setCreatedTime(new Date());
        apUserFriendRequest.setSuccess(0);
        apUserFriendRequest.setImage(apUser.getImage());
        apUserFriendRequestMapper.insert(apUserFriendRequest);

        ApUserMsg apUserMsg = new ApUserMsg();
        apUserMsg.setFromUser(apUserFriendRequest.getUserName());
        apUserMsg.setFromId(apUserFriendRequest.getUserId());
        apUserMsg.setContent(apUserMsg.getFromUser()+"请求添加您为好友");
        apUserMsg.setType(1);
        apUserMsg.setCreatedTime(new Date());
        apUserMsg.setUserId(apUserFriendRequest.getFriendId());
        apUserMsg.setIsRead(0);
//            apUserMsg.setArticleId(comment.getArticleId());
        apUserMsgMapper.insert(apUserMsg);

//            ApUser toUser = apUserMapper.selectById(apUserMsg.getUserId());

        GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "BC-b6050660635342f89d6b38039bfa2af0");
        goEasy.publish(apUserFriendRequest.getFriendName(), apUserMsg.getFromUser()+"申请成为您的好友", new PublishListener(){
            @Override
            public void onSuccess() {
                System.out.println("Publish success.");
            }

            @Override
            public void onFailed(GoEasyError error) {
                System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
            }
        });

        return ResponseResult.okResult("好友请求发送成功");
    }

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/uploadPicture")
    public ResponseResult uploadPicture(@RequestParam(value = "file") MultipartFile multipartFile, HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();
        log.info("上传图片的用户id为: {}",userId);

        if(multipartFile == null || multipartFile.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFileName = multipartFile.getOriginalFilename();
        String postfix = originalFileName.substring(originalFileName.lastIndexOf("."));
        Map<String,String> map = new HashMap<>();
        String fileId = null;
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")+1).toLowerCase();

        if(suffix.equals("mp4") || suffix.equals("avi") || suffix.equals("wmv") || suffix.equals("flv")){
            try {
                map = fileStorageService.uploadVideoFile("",fileName+postfix, multipartFile.getInputStream());
                log.info("上传视频 {} 成功",map.toString());
                return ResponseResult.okResult(map);
            } catch (IOException e) {
                log.info("上传视频失败");
                e.printStackTrace();
            }
        }
        String mimeType = multipartFile.getContentType();

        if(mimeType != null && mimeType.startsWith("audio")){
            try {
                fileId = fileStorageService.uploadAudio("",fileName+postfix,multipartFile.getInputStream());
                return ResponseResult.okResult(fileId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            fileId = fileStorageService.uploadImgFile("",fileName+postfix, multipartFile.getInputStream());
            log.info("上传图片 {} 成功",fileId);
        } catch (IOException e) {
            log.info("上传图片失败");
            throw new RuntimeException(e);
        }
        return ResponseResult.okResult(fileId);
    }


    @PostMapping("/friendRequestList")
    public ResponseResult friendRequestList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>().eq("userId",userId).or().eq("friendId",userId);
        return ResponseResult.okResult(apUserFriendRequestMapper.selectList(queryWrapper));
    }



    @PostMapping("/follow/{acl_id}")
    public ResponseResult followOneAclUser(HttpServletRequest request, @PathVariable Integer acl_id){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        Acl_user acl_user = aclUserMapper.selectById(acl_id);
        ApUser apUser = apUserMapper.selectById(userId);

        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setFollowId(acl_id);
        apUserFollow.setFollowName(acl_user.getName());
        apUserFollow.setCreatedTime(new Date());
        apUserFollow.setLevel(1);
        apUserFollow.setUserId(userId);
        apUserFollow.setIsNotice(1);
        apUserFollowMapper.insert(apUserFollow);

        AclUserFan aclUserFan = new AclUserFan();
        aclUserFan.setUserId(acl_id);
        aclUserFan.setCreatedTime(new Date());
        aclUserFan.setFansId(userId);
        aclUserFan.setFansName(apUser.getName());
        aclUserFan.setLevel(1);
        aclUserFan.setIsDisplay(1);
        aclUserFan.setIsShieldComment(0);
        aclUserFan.setIsShieldLetter(0);
        aclUserFanMapper.insert(aclUserFan);


        acl_user.setFanNum(acl_user.getFanNum()+1);
        aclUserMapper.updateById(acl_user);

        return ResponseResult.okResult("关注成功");
    }

    @PostMapping("/unfollow/{acl_id}")
    public ResponseResult unFollowOneAclUser(HttpServletRequest request, @PathVariable Integer acl_id){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());


        QueryWrapper queryWrapper_ap = new QueryWrapper<>();
        queryWrapper_ap.eq("user_id",userId);
        queryWrapper_ap.eq("follow_id",acl_id);
        apUserFollowMapper.delete(queryWrapper_ap);

        QueryWrapper queryWrapper_acl = new QueryWrapper<>();
        queryWrapper_acl.eq("user_id",acl_id);
        queryWrapper_acl.eq("fans_id",userId);
        aclUserFanMapper.delete(queryWrapper_acl);

        Acl_user acl_user = aclUserMapper.selectById(acl_id);
        acl_user.setFanNum(acl_user.getFanNum()-1);
        aclUserMapper.updateById(acl_user);
        return ResponseResult.okResult("取消关注成功");
    }

    @PostMapping("/followList")
    public ResponseResult getFollowList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

//        QueryWrapper queryWrapper = new QueryWrapper<ApUserFollow>();
//        queryWrapper.eq("follow_id",userId);
        System.out.println("user_id "+userId);
        return ResponseResult.okResult(apUserFollowMapper.getFollowerList(userId));
    }

    @PostMapping("/followNum")
    public ResponseResult getFollowNum(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        return ResponseResult.okResult(apUserFollowMapper.selectCount(queryWrapper));
    }

    @PostMapping("/friendNum")
    public ResponseResult getFriendNum(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        return ResponseResult.okResult(apUserRelationMapper.selectCount(queryWrapper));
    }

    @PostMapping("/otherFollowNum/{id}")
    public ResponseResult getFollowNum(HttpServletRequest request,@PathVariable("id") Integer id){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        return ResponseResult.okResult(apUserFollowMapper.selectCount(queryWrapper));
    }

    @PostMapping("/otherFriendNum/{id}")
    public ResponseResult getFriendNum(HttpServletRequest request,@PathVariable("id") Integer id){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",id);
        return ResponseResult.okResult(apUserRelationMapper.selectCount(queryWrapper));
    }

    @PostMapping("/getCommentNum")
    public ResponseResult getCommentNum(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        return commentService.getCommentNum(userId);
    }

    @PostMapping("/getOtherCommentNum/{name}")
    public ResponseResult getOtherCommentNum(@PathVariable("name") String name){

        return commentService.getOtherCommentNum(name);
    }

    @Autowired
    private iArticleClient iArticleClient;

    @PostMapping("/getArticleByAclId/{id}")
    public ResponseResult getArticleByAclId(@PathVariable("id") Integer id){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("author_id",id);
        return iArticleClient.getArticleByAclId(id);
    }

    @Autowired
    private ApCommentThumbMapper apCommentThumbMapper;



    @PostMapping("/getThumbNum/{name}")
    public ResponseResult getThumbNum(@PathVariable("name") String name){
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("name",name);
//        ApUser apUser = apUserMapper.selectOne(queryWrapper);
//
//        QueryWrapper queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("userId",apUser.getId());
//        Integer count1 = apCommentThumbMapper.selectCount(queryWrapper1);
//
//        ResponseResult commentsNum = iArticleClient.getCommentsNum(apUser.getId());
//        Integer count2 = (Integer) commentsNum.getData();
//
//        return ResponseResult.okResult(count1+count2);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        ApUser apUser = apUserMapper.selectOne(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("toId",apUser.getId());
        return ResponseResult.okResult(apCommentThumbMapper.selectCount(queryWrapper1));
    }

    @PostMapping("/thumbList")
    public ResponseResult getThumbList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());

        return ResponseResult.okResult(apCollectionDtoMapper.getThumbArticles(userId));
    }

    @PostMapping("/getSelfInfo")
    public ResponseResult getSelfInfo(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());
        ApUser user = apUserMapper.selectById(userId);

        return ResponseResult.okResult(user);
    }

    @PostMapping("/getUserInfo/{name}")
    public ResponseResult getUserInfo(HttpServletRequest request,@PathVariable("name") String name){
        QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);

        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.valueOf(claims.get("id").toString());
        ApUser user = apUserMapper.selectById(userId);

        ApUser other = apUserMapper.selectOne(queryWrapper);
//        if(user.getName().equals(other.getName())){
//            other.set();
//            return ResponseResult.okResult()
//        }

        QueryWrapper<ApUserRelation> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("friendName",user.getName());
        queryWrapper1.eq("userName",other.getName());
//            log.info("friendName {}",apUser.getName());
//            log.info("userName {}",user.getName());
        ApUserRelation apUserRelation = apUserRelationMapper.selectOne(queryWrapper1);
        if(apUserRelation == null){
            other.setFriend(false);
        }else {
            other.setFriend(true);
        }
//        log.info("apUserList {}", Arrays.toString(apUserList.toArray()));

        return ResponseResult.okResult(other);
    }


    @Autowired
    private CommentService commentService;

    /*
    发表评论
     */
    @PostMapping("/saveComment")
    public ResponseResult saveComment(HttpServletRequest request,@RequestBody Comment comment){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        ApUser ap_user = apUserMapper.selectById(userId);
        System.out.println(userId);
        System.out.println(comment);
        System.out.println(ap_user);

//        Comment comment1 = new Comment();
//        comment1.setContent("www");
//        comment1.setArticleId("1111");
//        comment1.setCreatedTime(new Date());
//        comment1.setNickname("admin");
//        comment1.setParentId("1302862387124125698");
//        comment1.setLikeNum(1);
//        comment1.setReplyNum(1);
//        comment1.setUserId("2");
        comment.setUserId(userId.toString());
        comment.setNickname(ap_user.getName());
        comment.setCreatedTime(new Date());
        return commentService.saveComment(comment,ap_user);
    }

    /*
    查询文章的所有评论
     */
    @PostMapping("/commentsByArticle/{id}")
    public ResponseResult getAllCommentsByArticle(HttpServletRequest request,@PathVariable("id") String id){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        String userId = claims.get("id").toString();

        return commentService.findCommentsByArticleId(id,userId);
    }

    /*
    查询用户的所有评论
     */
    @PostMapping("/commentsByUser")
    public ResponseResult getAllCommentsByUser(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        return commentService.findCommentsByUserId(userId);
    }

    @PostMapping("/getUserByUserName/{name}")
    public ResponseResult getUserByUserName(@PathVariable("name") String name){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        ApUser apUser = apUserMapper.selectOne(queryWrapper);

        return ResponseResult.okResult(apUser);
    }

    @Autowired
    private ApUserMsgMapper apUserMsgMapper;

    @PostMapping("/delMsgList/{fname}")
    public ResponseResult delMsgList(@PathVariable("fname") String fname,HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        ApUser my = apUserMapper.selectById(userId);
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",my.getName());
        queryWrapper.eq("friendName",fname);
        apUserMsgListMapper.delete(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("friendName",my.getName());
        queryWrapper1.eq("userName",fname);
        apUserMsgListMapper.delete(queryWrapper1);

        return ResponseResult.okResult("删除成功");
    }

    @PostMapping("/getMsgList")
    public ResponseResult getMsgList(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<ApUserMsg> list = apUserMsgMapper.selectList(queryWrapper);
        Collections.reverse(list);
        return ResponseResult.okResult(list);
    }

    @PostMapping("/getMsgNum")
    public ResponseResult getMsgNum(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("isRead",0);
        return ResponseResult.okResult(apUserMsgMapper.selectCount(queryWrapper));
    }

    @PostMapping("/readMsg")
    public ResponseResult readMsg(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("isRead",0);
        List<ApUserMsg> list = apUserMsgMapper.selectList(queryWrapper);
        for(ApUserMsg apUserMsg : list){
            apUserMsg.setIsRead(1);
            apUserMsgMapper.updateById(apUserMsg);
        }

        return ResponseResult.okResult("读取消息成功");
    }

    /*
    点赞点赞,id 评论id
     */
    // TODO 文章点赞等待完善
    @PostMapping("/likeComment/{id}")
    public ResponseResult likeComment(@PathVariable("id") String id,HttpServletRequest request) throws ParseException {
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        ApUser apUser = apUserMapper.selectById(userId);

        return commentService.likeComment(id,userId);
    }

    @PostMapping("unLikeComment/{id}")
    public ResponseResult unLikeComment(@PathVariable("id") String id,HttpServletRequest request) throws ParseException {
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        return commentService.unLikeComment(id,userId);
    }

    @PostMapping("/delComment/{id}")
    public ResponseResult delComment(@PathVariable("id") String id,HttpServletRequest request) throws ParseException {
        return commentService.delComment(id);
    }

    private static RedisCache redisCache;

    @PostMapping("/shareNews/{articleId}")
    public ResponseResult shareNews(@PathVariable("articleId") String articleId,HttpServletRequest request,@RequestBody List<ApUserRelation> apUserRelationList){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        ApUser from = apUserMapper.selectById(userId);
        ResponseResult article = iArticleClient.getArticleByArticleId(articleId);
        System.out.println("article "+article.toString());
        for (int i = 0; i < apUserRelationList.size(); i++) {
            ApUser to = apUserMapper.selectById(apUserRelationList.get(i).getFriendId());
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(article.getData()));
            ApArticle apArticle = JSON.toJavaObject(jsonObject, ApArticle.class);

            redisCache = SpringUtils.getBean(RedisCache.class);

            System.out.println("apUserRelationList "+apUserRelationList.get(i));
            insertFromLatestData(redisCache,from,to, apArticle,apUserRelationList.get(i));
            insetToLatestData(redisCache,from,to, apArticle,apUserRelationList.get(i));
//

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userName",from.getName());
            queryWrapper.eq("friendName",to.getName());
            ApUserMsgList from_list = apUserMsgListMapper.selectOne(queryWrapper);
            from_list.setContent("分享消息");
            from_list.setCreatedTime(new Date());
            from_list.setContentType(6);
            apUserMsgListMapper.updateById(from_list);

            QueryWrapper queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("userName",to.getName());
            queryWrapper1.eq("friendName",from.getName());
            ApUserMsgList to_list = apUserMsgListMapper.selectOne(queryWrapper1);
            to_list.setContent("分享消息");
            to_list.setCreatedTime(new Date());
            to_list.setContentType(6);
            apUserMsgListMapper.updateById(to_list);
        }
        return ResponseResult.okResult("分享成功");
    }

    public List<Message> insertFromLatestData(RedisCache redisCache, ApUser from, ApUser to, ApArticle apArticle,ApUserRelation apUserRelation){
        String new_listJson = redisCache.get(MessageConstants.FROM + from.getName() + MessageConstants.TO + to.getName());
        List<Message> msgList = null;
        if(new_listJson == null){
            msgList = new ArrayList<>();
        }else{
            msgList = JSON.parseObject(new_listJson, new TypeReference<List<Message>>(){});
        }

        if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
            Message message1 = new Message();
            message1.setCreatedTime(new Date());
            message1.setUsername(from.getName());
            message1.setImage(from.getImage());
            message1.setFrom(from.getName());
            message1.setTo(to.getName());
            message1.setId(UUID.randomUUID().toString());
            message1.setContentType(1);
            message1.setContent(apUserRelation.getMessage());
            msgList.add(message1);
        }
//

        Message message = new Message();
        message.setApArticle(apArticle);
        message.setCreatedTime(new Date());
        message.setUsername(from.getName());
        message.setImage(from.getImage());
        message.setFrom(from.getName());
        message.setTo(to.getName());
        message.setId(UUID.randomUUID().toString());
        message.setContentType(6);

        msgList.add(message);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",from.getName());
        queryWrapper.eq("friendName",to.getName());
        ApUserMsgList apUserMsgList = apUserMsgListMapper.selectOne(queryWrapper);
        if(apUserMsgList == null){
            if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
                ApUserMsgList new_apUserMsgList = new ApUserMsgList();
                new_apUserMsgList.setUserName(from.getName());
                new_apUserMsgList.setFriendName(to.getName());
                new_apUserMsgList.setMsgNum(2);
                new_apUserMsgList.setContent("分享消息");
                new_apUserMsgList.setImage(to.getImage());
                new_apUserMsgList.setContentType(6);
                new_apUserMsgList.setCreatedTime(new Date());
                apUserMsgListMapper.insert(new_apUserMsgList);
            }else{
                ApUserMsgList new_apUserMsgList = new ApUserMsgList();
                new_apUserMsgList.setUserName(from.getName());
                new_apUserMsgList.setFriendName(to.getName());
                new_apUserMsgList.setMsgNum(1);
                new_apUserMsgList.setContent("分享消息");
                new_apUserMsgList.setImage(to.getImage());
                new_apUserMsgList.setContentType(6);
                new_apUserMsgList.setCreatedTime(new Date());
                apUserMsgListMapper.insert(new_apUserMsgList);
            }
        }else{
            if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
                apUserMsgList.setMsgNum(apUserMsgList.getMsgNum()+2);
            }else{
                apUserMsgList.setMsgNum(apUserMsgList.getMsgNum()+1);
            }
            apUserMsgListMapper.updateById(apUserMsgList);
        }




        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userName",to.getName());
        queryWrapper1.eq("friendName",from.getName());
        ApUserMsgList apUserMsgList1 = apUserMsgListMapper.selectOne(queryWrapper1);
        if(apUserMsgList1 == null){
            if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
                ApUserMsgList new_apUserMsgList = new ApUserMsgList();
                new_apUserMsgList.setUserName(to.getName());
                new_apUserMsgList.setFriendName(from.getName());
                new_apUserMsgList.setMsgNum(2);
                new_apUserMsgList.setContent("分享消息");
                new_apUserMsgList.setCreatedTime(new Date());
                new_apUserMsgList.setContentType(6);
                new_apUserMsgList.setImage(from.getImage());
                apUserMsgListMapper.insert(new_apUserMsgList);
            }else{
                ApUserMsgList new_apUserMsgList = new ApUserMsgList();
                new_apUserMsgList.setUserName(to.getName());
                new_apUserMsgList.setFriendName(from.getName());
                new_apUserMsgList.setMsgNum(1);
                new_apUserMsgList.setContent("分享消息");
                new_apUserMsgList.setImage(from.getImage());
                new_apUserMsgList.setCreatedTime(new Date());
                new_apUserMsgList.setContentType(6);
                apUserMsgListMapper.insert(new_apUserMsgList);
            }
        }else{
            if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
                apUserMsgList1.setMsgNum(apUserMsgList1.getMsgNum()+2);
            }else{
                apUserMsgList1.setMsgNum(apUserMsgList1.getMsgNum()+1);
            }
            apUserMsgListMapper.updateById(apUserMsgList1);
        }




        redisCache.set(MessageConstants.FROM + from.getName() + MessageConstants.TO + to.getName(),JSON.toJSONString(msgList));
        return msgList;
    }

    public List<Message> insetToLatestData(RedisCache redisCache,ApUser from,ApUser to,ApArticle apArticle,ApUserRelation apUserRelation){
        String new_listJson = redisCache.get(MessageConstants.FROM + to.getName() + MessageConstants.TO + from.getName());
        List<Message> msgList = null;
        if(new_listJson == null){
            msgList = new ArrayList<>();
        }else{
            msgList = JSON.parseObject(new_listJson, new TypeReference<List<Message>>(){});
        }

        if(("1".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0) || ("0".equals(apUserRelation.getType()) && apUserRelation.getMessage().length() > 0)){
            Message message1 = new Message();
            message1.setCreatedTime(new Date());
            message1.setUsername(from.getName());
            message1.setImage(from.getImage());
            message1.setFrom(from.getName());
            message1.setTo(to.getName());
            message1.setId(UUID.randomUUID().toString());
            message1.setContentType(1);
            message1.setContent(apUserRelation.getMessage());
            msgList.add(message1);
        }

//

        Message message = new Message();
        message.setApArticle(apArticle);
        message.setCreatedTime(new Date());
        message.setUsername(from.getName());
        message.setImage(from.getImage());
        message.setFrom(from.getName());
        message.setTo(to.getName());
        message.setId(UUID.randomUUID().toString());
        message.setContentType(6);

        msgList.add(message);
        redisCache.set(MessageConstants.FROM + to.getName() + MessageConstants.TO + from.getName(),JSON.toJSONString(msgList));
        return msgList;
    }

    @PostMapping("/getReplyData")
    public ResponseResult getReplyData(HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        return commentService.getReplyData(userId);
    }

    @Autowired
    private ApUserVideoStatusMapper apUserVideoStatusMapper;

    @PostMapping("/addVideoStatus/{name}")
    public ResponseResult addVideoStatus(@PathVariable("name") String name,HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("name",name);
        ApUser from = apUserMapper.selectById(userId);
        ApUser to = apUserMapper.selectOne(queryWrapper);

        ApUserVideoStatus apUserVideoStatus = new ApUserVideoStatus();
        apUserVideoStatus.setUserId(userId);
        apUserVideoStatus.setUserName(from.getName());
        apUserVideoStatus.setFriendName(name);
        apUserVideoStatus.setFriendId(to.getId());
        apUserVideoStatusMapper.insert(apUserVideoStatus);

        ApUserVideoStatus apUserVideoStatus1 = new ApUserVideoStatus();
        apUserVideoStatus1.setUserId(to.getId());
        apUserVideoStatus1.setUserName(name);
        apUserVideoStatus1.setFriendName(from.getName());
        apUserVideoStatus1.setFriendId(from.getId());
        apUserVideoStatusMapper.insert(apUserVideoStatus1);

        return ResponseResult.okResult("添加通话记录成功");
    }

    @PostMapping("/delVideoStatus/{name}")
    public ResponseResult delVideoStatus(@PathVariable("name") String name, HttpServletRequest request){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        ApUser from = apUserMapper.selectById(userId);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName",from.getName());

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userName",name);

        apUserVideoStatusMapper.delete(queryWrapper);
        apUserVideoStatusMapper.delete(queryWrapper1);

        return ResponseResult.okResult("删除通话记录成功");
    }

    @PostMapping("/getVideoStatus/{name}")
    public ResponseResult getVideoStatus(HttpServletRequest request,@PathVariable("name") String name){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("userName",name);

        ApUserVideoStatus to = apUserVideoStatusMapper.selectOne(queryWrapper);
        if(to == null){
            return ResponseResult.okResult("free");
        }else{
            return ResponseResult.okResult("busy");
        }
    }

    @PostMapping("/addNewMsg/{toId}")
    public ResponseResult addNewMsg(HttpServletRequest request,@PathVariable("toId") Integer toId){
        String token = request.getHeader("ap_token");
        Jws<Claims> jws = AppJwtUtil.getJws(token);
        Claims claims = jws.getBody();
        Integer userId = Integer.parseInt(claims.get("id").toString());
        ApUser from = apUserMapper.selectById(userId);
        ApUser to = apUserMapper.selectById(toId);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",from.getName());
        queryWrapper.eq("friendName",to.getName());
        ApUserMsgList msgList = apUserMsgListMapper.selectOne(queryWrapper);

//        QueryWrapper queryWrapper1 = new QueryWrapper<>();
//        queryWrapper1.eq("userName",to.getName());
//        queryWrapper1.eq("friendName",from.getName());
//        apUserMsgListMapper.selectOne(queryWrapper);
        if(msgList == null){
            ApUserMsgList apUserMsgList = new ApUserMsgList();
            apUserMsgList.setMsgNum(0);
            apUserMsgList.setUserName(from.getName());
            apUserMsgList.setContent(null);
            apUserMsgList.setContentType(1);
            apUserMsgList.setFriendName(to.getName());
            apUserMsgList.setCreatedTime(new Date());
            apUserMsgList.setImage(to.getImage());

            apUserMsgListMapper.insert(apUserMsgList);

            ApUserMsgList apUserMsgList1 = new ApUserMsgList();
            apUserMsgList1.setMsgNum(0);
            apUserMsgList1.setUserName(to.getName());
            apUserMsgList1.setContent(null);
            apUserMsgList1.setContentType(1);
            apUserMsgList1.setFriendName(from.getName());
            apUserMsgList1.setCreatedTime(new Date());
            apUserMsgList1.setImage(from.getImage());

            apUserMsgListMapper.insert(apUserMsgList1);
            return ResponseResult.okResult("新建成功");
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
    }
}
